class ShippingMethod < ActiveRecord::Base
  has_many                  :orders
  validates_presence_of     :type
  validates_presence_of     :cost
  validates_numericality_of :cost
  
  after_destroy             :ensure_atleast_one_shipping_method_persists
  after_destroy             :find_and_change_effected_items
  
protected
  def find_and_change_effected_items
    self.orders.each {|order| order.update_attributes!(:shipping_method => ShippingMethod.find(:all, :order => 'cost asc').first)}
  end
  def ensure_atleast_one_shipping_method_persists
    ShippingMethod.create!(:name => "N/A", :cost => "0.0") if ShippingMethod.find(:all).empty?
  end
end
